<?php

namespace app\common\model;

class ShopCartModel extends BaseModel
{
    protected $name = 'shop_cart'; //定义用户表
    //开启自动写入时间戳
    protected $autoWriteTimestamp = false;
    // 定义自动完成的属性
    protected $auto = []; //新增修改
    protected $insert = []; //插入
    protected $update = []; //修改

    /**
     * 增加购物车
     * @param $buyerUid 买家ID
     * @param $skuInfo 商品信息
     * @param $number
     * @return bool
     */
    function addCart($buyerUid, $skuInfo, $number)
    {
        if($skuInfo['bl_id']>0){
            //检测购物车是否存在该数据
            $cartInfo = $this->where('buyer_uid', $buyerUid)->where('bl_id', $skuInfo['bl_id'])->find();
            if($cartInfo){
                $this->where('cart_id', $cartInfo['cart_id'])->setField('cart_num',$number);
            }else{
                $skuInfo['buyer_uid'] = $buyerUid;
                $skuInfo['create_time'] = time();
                $this->addData($skuInfo);
            }
        }else{
            $goodsModel = new ShopGoodsModel();
            //阶梯价计算
            $resultPrice = $goodsModel->calcPrice($skuInfo['goods_price'],$number);
            if ($resultPrice == false) {
                $this->error = $goodsModel->getError();
                return false;
            }
            //检测购物车是否存在该数据
            $cartInfo = $this->where('buyer_uid', $buyerUid)->where('sku_id', $skuInfo['sku_id'])->find();
            //加入购物车
            if ($cartInfo) { //更新
                $saveData = ['cart_num' => $number, 'cart_price' => $resultPrice];
                $this->where('cart_id', $cartInfo['cart_id'])->update($saveData);
            } else { //新增
                $skuInfo['buyer_uid'] = $buyerUid;
                $skuInfo['cart_price'] = $resultPrice;
                $skuInfo['cart_num'] = $number;
                $skuInfo['create_time'] = time();
                $skuInfo['bl_id'] = 0;
                $this->addData($skuInfo);
            }
        }
        return true;
    }

    /**
     * 购物车列表
     * @param array $map
     * @return mixed
     */
    public function cartList($map)
    {
        $cartList = $this->where($map)->select();
        $cartList = $cartList->isEmpty() ? [] : $cartList->toArray();
        return $cartList;
    }

    /**
     * 删除购物车
     * @param $ids 主键
     * @param $uid 用户ID
     * @return mixed
     */
    public function delCart($map)
    {
        $this->where($map)->delete();
        return true;
    }

    /**
     * 刷新购物车
     * @param $cartList
     * @return bool
     */
    public function refreshCart($cartList)
    {
        //刷新正常商品
        $cartList = $this->_getOnlineCartList($cartList);
        //刷新优惠套装
        $this->_getBundlingCartList($cartList);
        //赠品
        $this->_getGiftCartList($cartList);
        return $cartList;
    }

    /**
     * 刷新正常购物车商品
     * @param $cartList
     */
    private function _getOnlineCartList($cartList)
    {
        if (empty($cartList) || !is_array($cartList)) return $cartList;
        //验证商品是否有效
        $skuIds = [];
        foreach ($cartList as $v) {
            if ($v['bl_id'] == 0) { //排除套餐
                $skuIds[] = $v['sku_id'];
            }
        }
        $skuList = goods_all_list(0, 0, 50, ['sku_id'=>['in', $skuIds]]);
        $sku=[];
        foreach ($skuList as $v) {
            $sku[$v['sku_id']] = $v;
        }
        foreach ($cartList as $key => $value) {
            if ($value['bl_id'] > 0) continue; //排除套餐
            $cartList[$key]['state']       = true; //商品状态
            $cartList[$key]['stock_state'] = true; //库存状态
            if (in_array($value['sku_id'], array_keys($sku))) {
                $skuInfo                          = $sku[$value['sku_id']];
                $cartList[$key]['goods_name']     = $skuInfo['goods_name'];
                $cartList[$key]['goods_thumb']    = $skuInfo['goods_thumb'];
                $cartList[$key]['simple_price']   = $skuInfo['simple_price'];
                $cartList[$key]['goods_price']    = $skuInfo['goods_price'];
                $cartList[$key]['goods_freight']  = $skuInfo['goods_freight'];
                $cartList[$key]['goods_stock']    = $skuInfo['goods_stock'];
                $cartList[$key]['have_gift']      = $skuInfo['have_gift'];
                $cartList[$key]['step']           = $skuInfo['step'];
                $cartList[$key]['minimum']        = $skuInfo['minimum'];
                $cartList[$key]['promotion_type'] = $skuInfo['promotion_type'];
                if ($value['cart_num'] > $skuInfo['goods_stock']) {
                    $cartList[$key]['stock_state'] = false;
                }
                if ($skuInfo['promotion_type'] == 1) { //限时秒杀
                    $cartList[$key]['promotion_label'] = '限时秒杀';
                    $cartList[$key]['promotion_price'] = $skuInfo['promotion_price'];
                }
                if ($skuInfo['promotion_type'] == 4) { //限时抢购
                    $cartList[$key]['promotion_label'] = '限时抢购';
                    $cartList[$key]['promotion_price'] = $skuInfo['promotion_price'];
                }
            } else {
                //如果商品下架
                $cartList[$key]['state']       = false;
                $cartList[$key]['stock_state'] = false;
            }
        }
        return $cartList;
    }

    /**
     * 刷新优惠套装
     * @param $cartList
     * @return array
     */
    private function _getBundlingCartList(& $cartList)
    {
        if (empty($cartList) || !is_array($cartList)) return;
        foreach ($cartList as $key => $value) {
            if ($value['bl_id'] == 0) continue; //跳过非优惠套装
            $cartList[$key]['state']       = true;
            $cartList[$key]['stock_state'] = true;
            $bundlingModel                 = new ShopBundlingModel();
            $bundlingGoodsModel            = new ShopBundlingGoodsModel();
            $blInfo                        = $bundlingModel->where('bl_id', $value['bl_id'])->find(); //组合套装信息
            //标志优惠套装是否处于有效状态
            if (empty($blInfo) || $blInfo['status'] != 1) {
                $cartList[$key]['state'] = false;
            }
            //取得优惠套装商品列表
            $bl_goods_list     = $bundlingGoodsModel->where('bl_id', $value['bl_id'])->column('*', 'sku_id'); //全部赠品
            $bl_skulist        = goods_all_list(0, 0, 50, ['sku_id'=>['in', array_keys($bl_goods_list)]]); //正常销售赠品
            $bl_online_skulist = [];
            foreach ($bl_skulist as $k => $v) {
                $bl_online_skulist[$v['sku_id']] = $v;
            }
            unset($bl_skulist);
            foreach ($bl_goods_list as $skuid => $skuinfo) { //循环全部赠品
                if (array_key_exists($skuid, $bl_online_skulist)) { //存在
                    $skuInfo = $bl_online_skulist[$skuid];
                    //如果库存不足，标识false
                    if ($value['cart_num'] > $skuInfo['goods_stock']) {
                        $cartList[$key]['stock_state'] = false;
                    }
                    $cartList[$key]['goods_thumb']   = $skuInfo['goods_thumb'];
                    $cartList[$key]['simple_price']  = $skuInfo['simple_price'];
                    $cartList[$key]['goods_freight'] = $blInfo['bl_freight'];
                    $cartList[$key]['goods_stock']   = $skuInfo['goods_stock'];
                    $cartList[$key]['have_gift']     = $skuInfo['have_gift'];
                    $cartList[$key]['step']          = $skuInfo['step'];
                    $cartList[$key]['minimum']       = $skuInfo['minimum'];
                } else { //商品已经下架
                    $cartList[$key]['state']       = false;
                    $cartList[$key]['stock_state'] = false;
                }
            }
            $cartList[$key]['bl_sku_info'] = $blInfo->toArray();
            $cartList[$key]['bl_sku_list'] = $bl_goods_list;
        }
    }

    /**
     * 刷新购物车赠品
     * @param $cartList
     */
    private function _getGiftCartList(& $cartList)
    {
        foreach ($cartList as $key => $value) {
            if ($value['bl_id'] > 0) continue; //有组合套餐不赠送商品
            $gift_list = $this->_getGoodsGiftList($value); //获取赠品列表
            if (!empty($gift_list)) {
                $cartList[$key]['gift_list'] = $gift_list;
            }
        }
    }

    /**
     * 取得某商品赠品列表信息
     * @param array $goods_info
     */
    private function _getGoodsGiftList($skuInfo)
    {
        if (!$skuInfo['have_gift']) return [];
        $goodsModel     = new ShopGoodsModel();
        $goodsGiftModel = new ShopGoodsGiftModel();
        $gift_list      = $goodsGiftModel->getGiftList($skuInfo['sku_id']);
        if (empty($gift_list)) return [];
        $gift_list = $gift_list->toArray();
        foreach ($gift_list as $k => $v) {
            $online = $goodsModel->getSkuInfo($v['gift_sku_id']);
            if (empty($online)) { //商品不存在
                unset($gift_list[$k]);
            }
            if ($v['gift_num'] > $online['goods_stock']) { //去除库存不够的
                unset($gift_list[$k]);
            }
        }
        return $gift_list;
    }

    /**
     * 取得哪些店铺有满免运费活动
     * @param array $siteIds 店铺ID数组
     * @return array
     */
    public function getFreeFreightActiveList($siteIds) {
        if (empty($siteIds) || !is_array($siteIds)) return [];
        //定义返回数组
        $site_free_freight = [];
        //如果商品金额未达到免运费设置下线，则需要计算运费
        $map['site_id'] = ['in',$siteIds];
        $siteModel = new SiteModel();
        $siteList = $siteModel->field('site_id,site_free_price')->where($map)->select();
        foreach ($siteList as $siteInfo) {
            $free_price = floatval($siteInfo['site_free_price']);
            if ($free_price > 0) {
                $site_free_freight[$siteInfo['site_id']] = sprintf('满%s免运费',$free_price);
            }
        }
        return $site_free_freight;
    }
}